package com.damn;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.damn.bean.*;
import com.oreilly.servlet.MultipartRequest;
import com.restfb.DefaultWebRequestor;
import com.restfb.WebRequestor.Response;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FBService {
	public String storeCode(String codeStr,String username)	{
		
		String returnStr = "fail";
		Connection conn = DBService.getConnection();
		try	{
			if(conn != null)	{
				PreparedStatement st = conn.prepareStatement("Update token_master set code = ? where username = ? ");
				st.setString(1, codeStr);
				st.setString(2,	username);				
				st.executeUpdate();
				returnStr = "success";
				conn.close();
			}
		}
		catch (Exception e)	{
			e.printStackTrace();
			returnStr = "fail";
		}			
		return returnStr;
	}
	
public String storeToken(String tokenStr,String username)	{
		
		String returnStr = "fail";
		Connection conn = DBService.getConnection();
		try	{
			
			if(conn != null)	{
				System.out.println("IN");
				PreparedStatement st = conn.prepareStatement("Update token_master set token = ? , GP_COL1 = ? , GP_COL2 = ? where username = ? ");
				st.setString(1, tokenStr);
				st.setString(2,"1");
				st.setString(3,"Profile");
				st.setString(4,	username);				
				st.executeUpdate();
				conn.close();
				returnStr="success";
			}			
		}
		catch (Exception e)	{
			e.printStackTrace();
			returnStr = "fail";
		}		
		System.out.println(returnStr);
		return returnStr;
	}

public String storeUser(String uName,String Pwd)	{
	
	String returnStr = "fail";
	Connection conn = DBService.getConnection();	
	try	{
		if(conn != null)	{
			PreparedStatement chkSt = conn.prepareStatement("Select username from token_master where username = ?");
			chkSt.setString(1, uName);
			ResultSet rs = chkSt.executeQuery();
			while(rs.next())	{
				returnStr = "userExist";
			}			
			if(!returnStr.equalsIgnoreCase("userExist"))	{
				PreparedStatement st = conn.prepareStatement("Insert Into token_master (username,password) values (?,?)");
				st.setString(1, uName);
				st.setString(2,	Pwd);				
				st.executeUpdate();
				returnStr = "success";
			}			
			conn.close();
		}
	}
	catch (Exception e)	{
		e.printStackTrace();
		returnStr = "fail";
	}			
	return returnStr;
}

public ArrayList<GeneralBean> checkLogin(String uName,String Pwd)	{
		
	ArrayList<GeneralBean> listOfAccess =new ArrayList<GeneralBean>();
	Connection conn = DBService.getConnection();	
	try	{
		if(conn != null)	{
			PreparedStatement chkSt = conn.prepareStatement("Select * from token_master where username = ? and password = ?");
			chkSt.setString(1, uName);
			chkSt.setString(2, Pwd);
			ResultSet rs = chkSt.executeQuery();
			while(rs.next())	{
				GeneralBean bean = new GeneralBean();
				bean.setAccessIndex(rs.getString("gp_col1"));
				bean.setAccessName(rs.getString("gp_col2"));
				listOfAccess.add(bean);
			}			
			conn.close();
		}
	}
	catch (Exception e)	{
		e.printStackTrace();		
	}			
	return listOfAccess;
}

public ArrayList<String> getToken(String uName,String Pwd,ArrayList<String> indexList)	{
	
	ArrayList<String> tokenArray = new ArrayList<String>();
	Connection conn = DBService.getConnection();	
	try	{
		if(conn != null)	{			
			PreparedStatement chkSt = conn.prepareStatement("Select * from token_master where username = ? and password = ? ");
			chkSt.setString(1, uName);
			chkSt.setString(2, Pwd);			
			ResultSet rs = chkSt.executeQuery();
			while(rs.next())	{
				for(int index = 0;index<indexList.size();index++)	{
					if(rs.getString("gp_col1").equalsIgnoreCase(indexList.get(index)))	{
						String token = rs.getString("token");
						tokenArray.add(token);
					}
				}				
			}			
			conn.close();
		}
	}
	catch (Exception e)	{
		e.printStackTrace();		
	}			
	return tokenArray;
}

public String storeOthers( ArrayList<GeneralBean> listOfAccess, String uName)	{
	String responseStr = "";
	Connection conn = DBService.getConnection();	
	try	{
		if(conn != null)	{
			String pwd = "";
			PreparedStatement getPwd = conn.prepareStatement("select password from token_master where username = ? ");
			getPwd.setString(1, uName);
			ResultSet rs = getPwd.executeQuery();
			while(rs.next())	{
				pwd = rs.getString("password");
			}
			for(int index = 0;index<listOfAccess.size();index++)	{
				GeneralBean bean = listOfAccess.get(index);
				PreparedStatement chkSt = conn.prepareStatement("Insert into token_master(username,password,token,gp_col1,gp_col2) values (?,?,?,?,?)");
				chkSt.setString(1, uName);
				chkSt.setString(2, pwd);
				chkSt.setString(3, bean.getToken());
				chkSt.setString(4, bean.getAccessIndex());
				chkSt.setString(5, bean.getAccessName());
				chkSt.executeUpdate();			
			}		
			conn.close();
			responseStr = "success";
		}
	}
	catch (Exception e)	{
		e.printStackTrace();		
		responseStr = "fail";
	}			
	return responseStr;
}

public ArrayList<GeneralBean> getOtherAccess (String token)	{		
	/*
	String jsonStr = "{ \"data\": [{ \"name\": \"World of Pics\",\"access_token\": \"AAAE8ZBqo17MkBAFTROjP3Ig47qrw7ngBzd0cPtZBzZCzZCvZBvJ083jZCFxC3F6ghibuXsZC5x9WkXIMpZBxJKXoA2OLsDce0ex9IaEetUBQOmHmWhnq5POt\",\"category\": \"Entertainment\",\"id\":\"105617606228855\" }]}";
	JsonObject jsonObj = new JsonObject(jsonStr);
	System.out.println(jsonObj.get("name"));
	*/
	ArrayList<GeneralBean> listOfAccess = new ArrayList<GeneralBean>();
	DefaultWebRequestor connectHTTP = new DefaultWebRequestor();
	try {
		//token="AAAE8ZBqo17MkBAFKIEyHzkpG4g7cRiOKx68YOzZBv8ON1N7YrsYX6YDVZAwiKOArMvRkl2OzmspZC8ZCbE3Fnh3rqx8rrQZBPxb2DmYqbnxgZDZD";
		String url = "https://graph.facebook.com/me/accounts?access_token="+token;
		Response responseObj = connectHTTP.executeGet(url);
		if(responseObj.getStatusCode() == 200)	{
			String responseStr = responseObj.getBody();			
			responseStr = responseStr.substring(responseStr.indexOf("["), responseStr.lastIndexOf("]")+1);
			System.out.println("After Processing : "+responseStr);
			JSONArray jsonResponse = new JSONArray(responseStr);
			for(int index = 0;index<jsonResponse.length();index++)	{
				JSONObject jsonObj = jsonResponse.getJSONObject(index);
				GeneralBean bean = new GeneralBean();
				bean.setAccessIndex(String.valueOf(index+2));
				bean.setAccessName(jsonObj.getString("name"));
				bean.setToken(jsonObj.getString("access_token"));
				listOfAccess.add(bean);
				System.out.println(bean.getAccessName());
				System.out.println(bean.getToken());
			}		
		}		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (JSONException jsonE) {
		// TODO Auto-generated catch block
		jsonE.printStackTrace();
	}
	return listOfAccess;
}

public ArrayList<String> getAccessIndexArray(MultipartRequest multi)	{
	ArrayList<String> indexArray = new ArrayList<String>();
	String[] indexArray2 = multi.getParameterValues("access");		 
	for(int index = 0;index<indexArray2.length;index++)	{			
		String accessIndex = indexArray2[index];
		indexArray.add(accessIndex);		
	}
	return indexArray;
}

public String getParaFromReq(MultipartRequest multi,String paraName)	{
	if(multi.getParameter(paraName)!=null)	{
		return multi.getParameter(paraName);
	}
	else	{
		return "";
	}		
}

public String storeScheduleArray (ArrayList<FileScheduleBean> fileSchAr , String userName, ArrayList<String> profileIndexAr)	{		
	
	String responseStr = "";
	Connection conn = DBService.getConnection();	
	try	{
		if(conn != null)	{
			for(int index = 0;index<fileSchAr.size();index++)	{
				FileScheduleBean fileSchBean = fileSchAr.get(index);
				for(int prIndex = 0;prIndex < profileIndexAr.size();prIndex++)	{
					PreparedStatement chkSt = conn.prepareStatement("Insert into SCH_MASTER(ABS_PATH,TIME_HR,TIME_MIN,USER_ID,PROFILE_INDEX,ACTIVE,GP_COL1) values (?,?,?,?,?,?,?)");
					chkSt.setString(1, fileSchBean.getFilePath());
					chkSt.setString(2, fileSchBean.getSchHour());
					chkSt.setString(3, fileSchBean.getSchMin());
					chkSt.setString(4, userName);
					chkSt.setString(5, profileIndexAr.get(prIndex));
					chkSt.setString(6, "Y");
					chkSt.setString(7, fileSchBean.getCaption());
					chkSt.executeUpdate();
				}
			}
			conn.close();
			responseStr = "success";
		}
	}
	catch (Exception e)	{
		e.printStackTrace();		
		responseStr = "fail";
	}			
	return responseStr;
}

public String initSchedulePost()	{
	System.out.println("------------------------Schedular Log-------------------------");
	String responseStr = "";
	Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Kolkata"));	
	int curHour = calendar.get(Calendar.HOUR_OF_DAY);
	int curMin = calendar.get(Calendar.MINUTE);
	System.out.println("Time : Hour : "+curHour + " Min : " + curMin);
	
	ArrayList<FileScheduleBean> fileSchAr = new ArrayList<FileScheduleBean>();
	fileSchAr = getListOfSchPost(curHour,curMin);
	if(fileSchAr.size()>0)	{
		responseStr = postScheduled(fileSchAr);
		if(responseStr.equals("success"))	{
			deactivateCompleted(curHour,curMin);
		}
	}
	return responseStr;
}

public ArrayList<FileScheduleBean> getListOfSchPost(int hour,int min)	{
	
	ArrayList<FileScheduleBean> fileSchAr = new ArrayList<FileScheduleBean>();	
	Connection conn = DBService.getConnection();	
	try	{
		if(conn != null)	{
			System.out.println("Got Connection for getListOfSchPost");
			/*
			PreparedStatement chkSt = conn.prepareStatement("SELECT s.ABS_PATH,s.GP_COL1,t.TOKEN FROM SCH_MASTER s , TOKEN_MASTER t WHERE s.PROFILE_INDEX = t.GP_COL1 AND s.USER_ID = t.USERNAME AND s.ACTIVE='Y' AND s.TIME_HR <= ? AND s.TIME_MIN <= ?");				
			chkSt.setInt(1, hour);
			chkSt.setInt(2, min);			
			ResultSet rs = chkSt.executeQuery();
			while(rs.next())	{				
				FileScheduleBean fileSchBean = new FileScheduleBean();				
				fileSchBean.setFilePath(rs.getString("ABS_PATH"));
				fileSchBean.setCaption(rs.getString("GP_COL1"));
				fileSchBean.setFileName(rs.getString("TOKEN"));
				System.out.println("File Name : "+fileSchBean.getFilePath());
				System.out.println("Caption : "+fileSchBean.getCaption());
				fileSchAr.add(fileSchBean);
			}
			*/
			PreparedStatement chkSt = conn.prepareStatement("SELECT s.ABS_PATH,s.GP_COL1,s.PROFILE_INDEX,s.USER_ID FROM SCH_MASTER s WHERE s.ACTIVE='Y' AND s.TIME_HR <= ? AND s.TIME_MIN <= ?");
			chkSt.setInt(1, hour);
			chkSt.setInt(2, min);			
			ResultSet rs = chkSt.executeQuery();
			while(rs.next())	{				
				FileScheduleBean fileSchBean = new FileScheduleBean();				
				fileSchBean.setFilePath(rs.getString("ABS_PATH"));
				fileSchBean.setCaption(rs.getString("GP_COL1"));
				fileSchBean.setSchMin(rs.getString("PROFILE_INDEX"));	//Storing index in sch min
				fileSchBean.setSchHour(rs.getString("USER_ID"));
				System.out.println("File Name : "+fileSchBean.getFilePath());
				System.out.println("Caption : "+fileSchBean.getCaption());
				fileSchAr.add(fileSchBean);
			}
			if(fileSchAr!=null && fileSchAr.size()>0)	{			
				for(int i=0;i<fileSchAr.size();i++)	{
					chkSt = conn.prepareStatement("Select token from token_master t where t.username = ? and t.GP_COL1 = ?");
					chkSt.setString(1, fileSchAr.get(i).getSchHour());
					chkSt.setString(2, fileSchAr.get(i).getSchMin());
					rs = chkSt.executeQuery();
					while(rs.next())	{
						fileSchAr.get(i).setFileName(rs.getString("token"));
					}
				}
			}
			conn.close();
		}		
	}
	catch (Exception e)	{
		e.printStackTrace();		
	}		
	return fileSchAr;
}

public String postScheduled(ArrayList<FileScheduleBean> fileSchAr)		{	
	String responseStr = "";
	try {		
		for(int index = 0;index<fileSchAr.size();index++)	{
			FileScheduleBean fileSchBean = new FileScheduleBean();
			fileSchBean = fileSchAr.get(index);
			File uploadedFile = new File(fileSchBean.getFilePath());
			InputStream picStream = new BufferedInputStream(new FileInputStream(uploadedFile));
			RestFB fbClient= new RestFB();
			responseStr = fbClient.initFBClient(fileSchBean.getFileName());
			if(responseStr.equalsIgnoreCase("success"))	{
				responseStr = fbClient.publishPhoto(picStream, fileSchBean.getCaption());
			}			
		}
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		responseStr = "fail";
	}
	return responseStr;
}

public String deactivateCompleted(int hour,int min)	{
	String responseStr = "";	
	Connection conn = DBService.getConnection();	
	try	{
		if(conn != null)	{
			System.out.println("Got Connection for deactivateCompleted");
			PreparedStatement chkSt = conn.prepareStatement("UPDATE SCH_MASTER s SET s.ACTIVE = 'N' WHERE s.ACTIVE='Y' AND s.TIME_HR <= ? AND s.TIME_MIN <= ?");				
			chkSt.setInt(1, hour);
			chkSt.setInt(2, min);			
			chkSt.executeUpdate();			
			conn.close();
			responseStr="success";
		}		
	}
	catch (Exception e)	{
		e.printStackTrace();	
		responseStr = "fail";
	}		
	return responseStr;
}
}
